// 涓庢湇鍔″櫒鐨勮繛鎺ョ嚎绋�
package com.thread;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import com.config.ClientCfg;
import com.databus.*;

public class ServerConnect implements Runnable {
	
	public ServerConnect(MessageCallBack cb, ClientCfg cfg)
	{
		mCallBack = cb;
		mClientCfg = cfg;
	}
	
	// 鑾峰彇鎺ユ敹缂撳啿鍖�
	public DataInputStream GetInputStream()
	{
		return mReceive;
	}
	
	// 鑾峰彇鍙戦�佺紦鍐插尯
	public DataOutputStream GetOutputStream()
	{
		return mSend;
	}
	
	// 杩炴帴鏈嶅姟鍣�
	protected boolean Connect(String addr, int port)
	{
		Log.info("Connect to server, addr = " + addr + " port = " + port);
		
		try {
			InetAddress address = InetAddress.getByName(addr);
			
			mSocket = new Socket();
			mSocket.connect(new InetSocketAddress(address, port), mClientCfg.mConnectTimeOut);
			
			mSend = new DataOutputStream(mSocket.getOutputStream());
			mReceive = new DataInputStream(mSocket.getInputStream());
			
			if (!mSocket.isConnected() || mSocket.isOutputShutdown()) 
			{
				Log.error("Socket disConnected or socket outputShutdown.");
				mSocket.close();
				mSend.close();
				mReceive.close();
				return false;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.error("Connect to server failed");
			return false;
		}

		return true;
	}
	
	// 鍏抽棴杩炴帴
	public void Close()
	{
		if(null != mSocket) {
			try {
				mSend.close();
				mReceive.close();
				mSocket.close();
				mSend    = null;
				mReceive = null;
				mSocket  = null;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		Log.info("Start Connect Thread...");
		
		int index = 0;
		while(!Connect(mClientCfg.mSrvAddrList.get(index).mAddr, mClientCfg.mSrvAddrList.get(index).mPort))
		{
			index++;
			index = index % mClientCfg.mSrvAddrList.size();
			
			try {
				Thread.sleep(mClientCfg.mBrokenInterval);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				break;
			}
		}
		Log.info("Connect Success!");
		
		if(null != mCallBack)
		{
			mCallBack.OnConnectChange(MessageCallBack.EConnectStatus.ConnectStatus_Online);
		}
		Log.info("End Connect Thread...");
	}
	
	
	private Socket mSocket = null;                        // 杩炴帴socket
	private DataOutputStream mSend = null;                // 鍙戦�佺紦鍐插尯
	private DataInputStream mReceive = null;              // 鎺ユ敹缂撳啿鍖�
	private ClientCfg mClientCfg = null;                  // 閰嶇疆鍙傛暟
	private MessageCallBack mCallBack = null;            // 娑堟伅鍥炶皟鎺ュ彛
}
